package com.yyaccp.hncc.oss.aliyun;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/8/19
 */
@RestController
@RequestMapping("/aliyun/oss")
@RequiredArgsConstructor
@Slf4j
public class OssController {
    private final OssService ossService;

    /**
     * 普通方式上传文件到阿里云oss
     * 可以通过下载获取该文件
     * @param desc 文件描述
     * @param files 上传的文件数组
     * @return 上传结果map，失败为empty map
     */
    @PostMapping("/upload")
    public Object upload(String desc, @RequestParam("files") MultipartFile[] files){
        if (files == null) {
            return "notfound upload files";
        }
        final Map<String, Object> result = new HashMap<>();
        Arrays.stream(files).forEach(multipartFile -> {
            String originalFilename = multipartFile.getOriginalFilename();
            try (InputStream in = multipartFile.getInputStream()){
                Map<String, Object> uploadResult = ossService.upload(originalFilename, in);
                result.put((String)uploadResult.get("filename"), uploadResult);
            } catch (IOException e) {
                log.error("上传文件-{}-失败", originalFilename,  e);
            }
        });
        return result;
    }

    /**
     * 根据文件名从oss下载文件到本地
     * @param filename 存储在oss上的唯一的文件名
     * @param response 无
     */
    @GetMapping("/download")
    public void download(String filename, HttpServletResponse response) {
        Assert.notNull(filename,"文件名不能为空");
        // 通用文件下载响应头设置
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        try (OutputStream out = response.getOutputStream()) {
            Map<String, Object> result = ossService.download(filename, out);
            log.info("下载文件{}成功，{}", filename, result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
